import React, { useState } from 'react'
import { activeThemeAtom } from '@/atoms'
import { useAtomValue } from 'jotai'
import { useTranslation } from 'react-i18next'
import clsx from 'clsx'
import { MessageType, MessageRoleEnum } from '@/types'
import { v7 as uuidv7 } from 'uuid'
import useChat from '@/hooks/useChat'
import useMessage from '@/hooks/useMessage'
import { showEditChatDialog } from '@/components/Dialogs/ChatEdit'
import { Typography, TextareaAutosize, Tooltip, IconButton } from '@mui/material'

export default function InputBox() {
  const { t } = useTranslation()
  const theme = useAtomValue(activeThemeAtom)
  const [messageInput, setMessageInput] = useState('')
  const [chatingStatus, setChatingStatus] = useState(false)
  const { abortResponse, getResMessage, generateChatTitle } = useChat()
  const { insertMessage } = useMessage()

  const stopChat = () => {
    abortResponse()
    setChatingStatus(false)
  }

  const handleSend = async () => {
    if (messageInput.trim() === '') {
      return
    }

    const useMessage: MessageType = {
      id: uuidv7(),
      role: MessageRoleEnum.User,
      content: messageInput,
      timestamp: new Date().getTime(),
    }

    insertMessage(useMessage)
    setMessageInput('')
    setChatingStatus(true)
    await getResMessage()
    setChatingStatus(false)
    generateChatTitle()
  }

  const onKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (
      event.code === 'Enter'
      && !event.shiftKey
      && !event.ctrlKey
      && !event.altKey
      && !event.metaKey
    ) {
      event.preventDefault()
      handleSend()
      return
    }
    if (event.code === 'Enter' && event.ctrlKey) {
      event.preventDefault()
      handleSend()
      return
    }
  }

  return (
    <div className="my-5 w-55vw flex flex-col rounded-lg bg-gray-100 shadow-inner dark:bg-gray-800">
      <TextareaAutosize
        maxRows={2}
        className={clsx('block min-h-2.5rem resize-none border-none bg-transparent p-2 text-1rem outline-none', {
          'text-white': theme == 'dark',
          'text-black': theme == 'light',
        })}
        style={{ fontFamily: 'inherit' }}
        value={messageInput}
        onChange={e => setMessageInput(e.target.value)}
        onKeyDown={onKeyDown}
        placeholder={t('write your message')}
      />
      <div className="h-2re}m flex items-center justify-between overflow-hidden p-2">
        <Tooltip title={t('chat setting tip')}>
          <IconButton color="primary" size="small" onClick={() => showEditChatDialog()}>
            <div className="i-material-symbols:display-settings" />
          </IconButton>
        </Tooltip>
        <div>
          {
            chatingStatus
              ? (
                  <IconButton color="primary" size="small" onClick={stopChat}>
                    <div className="i-material-symbols:stop-circle-rounded" />
                  </IconButton>
                )
              : (
                  <Tooltip
                    title={(
                      <Typography variant="caption">
                        {t('send btn tips')}
                      </Typography>
                    )}
                  >
                    <IconButton color="primary" size="small" onClick={handleSend}>
                      <div className="i-material-symbols:send-rounded" />
                    </IconButton>
                  </Tooltip>
                )
          }
        </div>
      </div>
    </div>
  )
}
